package websocket

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var ws_connect_list []*websocket.Conn

func init() {
	ws_connect_list = make([]*websocket.Conn, 0)
}

func WebsocketHandler(c *gin.Context) {
	//1.设置websocket参数，CheckOrigin表示是否允许跨域
	upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {
		return true
	}}
	//2.建立websocket连接
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("有新的websocket连接....")
	ws_connect_list = append(ws_connect_list, conn)
	fmt.Printf("websocket当前共有: %v个连接\n", len(ws_connect_list))

}

//发送websocket消息
func SendMsg(json interface{}) {
	for i, conn := range ws_connect_list {
		if conn != nil {
			//发送消息
			fmt.Printf("websockt发送消息地址 %v\n", conn.RemoteAddr().String())
			fmt.Printf("websockt发送消息%v\n", json)
			err := conn.WriteJSON(json)
			if err != nil {
				//把失效的conn都删了
				conn.Close()
				ws_connect_list[i] = nil
			}
		}
	}
	//把nil的元素过滤掉
	n := 0
	for _, x := range ws_connect_list {
		if x != nil {
			ws_connect_list[n] = x // 保留该元素
			n++
		}
	}
	ws_connect_list = ws_connect_list[:n] // 截取切片中需保留的元素
	fmt.Printf("websocket当前共有: %v个连接\n", len(ws_connect_list))
}
